package com.aisile.crowd_funding.system.controller;

import com.aisile.crowd_funding.common.annotion.Log;
import com.aisile.crowd_funding.common.controller.baseController;
import com.aisile.crowd_funding.common.utils.MD5Utils;
import com.aisile.crowd_funding.common.utils.R;
import com.aisile.crowd_funding.common.utils.StringUtils;
import com.aisile.crowd_funding.system.mapper.SysUserMapper;
import com.aisile.crowd_funding.system.pojo.SysUser;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


import java.util.List;

/**
 * @标题 LoginController
 * @作者 Mr.chen
 * @创建日期 2018/12/4 16:43
 * @版本号 1.0
 **/
@Controller
public class LoginController extends baseController {
    @Autowired
    SysUserMapper sysUserMapper;

    @RequestMapping(value = {"/",""})
    public String defaultPage(){
        return "redirect:index";
    }
    @RequestMapping("login")
    public String login(){
        List<SysUser> sysUsers = sysUserMapper.selectByExample(null);
        System.out.println(sysUsers);
        return "login";
    }
    @RequestMapping("index")
    public String index(Model m)
    {
       m.addAttribute("username",getUserName());
        return "/index";
    }

    @Log("登录方法")
    @RequestMapping("loginSign")
    @ResponseBody
    public R loginSign(String username,String password){

        //  效验参数
        if(StringUtils.isBlank(username)){
            return R.error("用户名不能为空");
        }
        if(StringUtils.isBlank(password)){
            return R.error("密码不能为空");
        }
        //认证创建一个subject对象
        org.apache.shiro.subject.Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(username, MD5Utils.encrypt(password));
        try {
            subject.login(usernamePasswordToken);
        }catch (UnknownAccountException e) {
            return  R.error("未查询到该用户");
        }catch(LockedAccountException e){
            return R.error("用户认证失败");
        }catch(Exception e){
            return  R.error("登录失败");
        }
        return R.ok();
    }
    @RequestMapping("/main")
    public String main(){
        return "main";
    }
}
